package com.sylar.tool.test.datasource;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@Component
//@WebFilter(filterName = "dsFilter", urlPatterns = {"/userInfo/*"})
public class DynamicDataSourceFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, ServletException, IOException {
        // 获取上下文信息，判断应该使用哪个数据源
        String dataSourceKey = determineDataSourceKey(request);
        // 设置数据源标识
        DynamicDataSourceContextHolder.push(dataSourceKey);
        try {
            // 继续处理请求
            chain.doFilter(request, response);
        } finally {
            // 清除数据源标识
            DynamicDataSourceContextHolder.poll();
        }
    }

    // 根据请求信息确定数据源标识
    private String determineDataSourceKey(ServletRequest request) {
        // 根据请求参数、请求头等进行逻辑判断，返回相应的数据源标识
        // ...
        return null;
    }

    // 其他方法实现，如初始化和销毁方法
    // ...
}
